import React, { useState, useEffect, useCallback } from 'react';
import {
  Form,
  Input,
  Select,
  Switch,
  Button,
  Card,
  Typography,
  Space,
  message,
  Row,
  Col,
  Divider,
} from 'antd';
import {
  SaveOutlined,
  ArrowLeftOutlined,
  ApiOutlined,
  RobotOutlined,
  BulbOutlined,
  CodeOutlined,
} from '@ant-design/icons';
import { useNavigate, useParams } from 'react-router-dom';
import { LlmModel, LlmModelCreateRequest, LlmModelUpdateRequest } from '../../types';
import { llmModelService } from '../../services/llmModels';
import { useTranslation } from 'react-i18next';

const { Title, Text } = Typography;
const { TextArea } = Input;
const { Option } = Select;

const LlmModelForm: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [isEdit, setIsEdit] = useState(false);
  const [model, setModel] = useState<LlmModel | null>(null);
  const navigate = useNavigate();
  const { id } = useParams<{ id: string }>();
  const { t } = useTranslation();

  const loadModel = useCallback(async (modelId: number) => {
    setLoading(true);
    try {
      const data = await llmModelService.getLlmModel(modelId);
      setModel(data);
      form.setFieldsValue({
        modelId: data.modelId,
        name: data.name,
        provider: data.provider,
        category: data.category,
        endpoint: data.endpoint,
        accessKey: data.accessKey,
        description: data.description,
        isEnabled: data.isEnabled,
      });
    } catch (error) {
      message.error(t('llmModels.loadError'));
      navigate('/llm-models');
    } finally {
      setLoading(false);
    }
  }, [form, navigate, t]);

  useEffect(() => {
    if (id && id !== 'create') {
      setIsEdit(true);
      loadModel(parseInt(id));
    }
  }, [id, loadModel]);

  const handleSubmit = async (values: any) => {
    setLoading(true);
    try {
      if (isEdit && model) {
        const updateData: LlmModelUpdateRequest = {
          modelId: values.modelId,
          name: values.name,
          provider: values.provider,
          category: values.category,
          endpoint: values.endpoint,
          accessKey: values.accessKey,
          description: values.description,
          isEnabled: values.isEnabled,
        };
        await llmModelService.updateLlmModel(model.id, updateData);
        message.success(t('llmModels.updateSuccess'));
      } else {
        const createData: LlmModelCreateRequest = {
          modelId: values.modelId,
          name: values.name,
          provider: values.provider,
          category: values.category,
          endpoint: values.endpoint,
          accessKey: values.accessKey,
          description: values.description,
          isEnabled: values.isEnabled ?? true,
        };
        await llmModelService.createLlmModel(createData);
        message.success(t('llmModels.createSuccess'));
      }
      navigate('/llm-models');
    } catch (error) {
      message.error(t('llmModels.saveError'));
    } finally {
      setLoading(false);
    }
  };

  const categoryOptions = [
    {
      value: 'Chat',
      label: (
        <Space>
          <RobotOutlined />
          {t('llmModels.chatModel')}
        </Space>
      ),
    },
    {
      value: 'Reasoning',
      label: (
        <Space>
          <BulbOutlined />
          {t('llmModels.reasoningModel')}
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ marginBottom: 24 }}>
        <Space>
          <Button
            icon={<ArrowLeftOutlined />}
            onClick={() => navigate('/llm-models')}
          >
            {t('common.back')}
          </Button>
          <Title level={2} style={{ margin: 0 }}>
            {isEdit ? t('llmModels.editModel') : t('llmModels.createModel')}
          </Title>
        </Space>
        <Text type="secondary">
          {isEdit ? t('llmModels.editDescription') : t('llmModels.createDescription')}
        </Text>
      </div>

      <Card>
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
          initialValues={{
            isEnabled: true,
            category: 'Chat',
          }}
        >
          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="modelId"
                label={t('llmModels.modelId')}
                rules={[
                  { required: true, message: t('llmModels.modelIdRequired') },
                  { max: 100, message: t('llmModels.modelIdMaxLength') },
                ]}
              >
                <Input
                  prefix={<CodeOutlined />}
                  placeholder={t('llmModels.modelIdPlaceholder')}
                />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="name"
                label={t('llmModels.name')}
                rules={[
                  { required: true, message: t('llmModels.nameRequired') },
                  { max: 100, message: t('llmModels.nameMaxLength') },
                ]}
              >
                <Input
                  prefix={<ApiOutlined />}
                  placeholder={t('llmModels.namePlaceholder')}
                />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="provider"
                label={t('llmModels.provider')}
                rules={[
                  { required: true, message: t('llmModels.providerRequired') },
                  { max: 50, message: t('llmModels.providerMaxLength') },
                ]}
              >
                <Input placeholder={t('llmModels.providerPlaceholder')} />
              </Form.Item>
            </Col>
          </Row>

          <Row gutter={24}>
            <Col span={12}>
              <Form.Item
                name="category"
                label={t('llmModels.category')}
                rules={[{ required: true, message: t('llmModels.categoryRequired') }]}
              >
                <Select placeholder={t('llmModels.categoryPlaceholder')}>
                  {categoryOptions.map(option => (
                    <Option key={option.value} value={option.value}>
                      {option.label}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="isEnabled"
                label={t('llmModels.status')}
                valuePropName="checked"
              >
                <Switch
                  checkedChildren={t('common.enabled')}
                  unCheckedChildren={t('common.disabled')}
                />
              </Form.Item>
            </Col>
          </Row>

          <Form.Item
            name="endpoint"
            label={t('llmModels.endpoint')}
            rules={[
              { required: true, message: t('llmModels.endpointRequired') },
              { max: 500, message: t('llmModels.endpointMaxLength') },
            ]}
          >
            <Input placeholder={t('llmModels.endpointPlaceholder')} />
          </Form.Item>

          <Form.Item
            name="accessKey"
            label={t('llmModels.accessKey')}
            rules={[
              { required: true, message: t('llmModels.accessKeyRequired') },
              { max: 500, message: t('llmModels.accessKeyMaxLength') },
            ]}
          >
            <Input.Password placeholder={t('llmModels.accessKeyPlaceholder')} />
          </Form.Item>

          <Form.Item
            name="description"
            label={t('llmModels.description')}
            rules={[{ max: 500, message: t('llmModels.descriptionMaxLength') }]}
          >
            <TextArea
              rows={4}
              placeholder={t('llmModels.descriptionPlaceholder')}
              showCount
              maxLength={500}
            />
          </Form.Item>

          <Divider />

          <Form.Item>
            <Space>
              <Button
                type="primary"
                htmlType="submit"
                icon={<SaveOutlined />}
                loading={loading}
              >
                {isEdit ? t('common.update') : t('common.create')}
              </Button>
              <Button onClick={() => navigate('/llm-models')}>
                {t('common.cancel')}
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default LlmModelForm;
